<template>
	<view>
		<view class="order-info" @click="handleModal()">
			<image :src="orderInfo.escortInfo.avatar" mode="aspectFit" />
			<view class="hospital-details">
				<view style="font-size: 33rpx;">{{ orderInfo.escortInfo.name }}</view>
				<view> {{ orderInfo.type }}</view>
				<view>{{ orderInfo.hospitalName }}</view>
			</view>
		</view>

		<!-- 模态框 -->
		<view ref="popup" class="modal-overlay" v-show="showModal && canPostReview">
			<view class="modal-content">
				<form @submit.prevent="handleSubmit">
					<scroll-view scroll-y class="form-scroll">
						<view class="form-item">
							<label>描述</label>
							<input v-model="formData.description" placeholder="请输入描述" required />
						</view>
						<view class="form-item">
							<label>评分</label>
							<input v-model="formData.score" placeholder="请输入评分" required />
						</view>

						<!-- 描述图片上传 -->
						<view class="form-item">
							<label>评价图片</label>
							<button @click="chooseFiles">选择图片</button>
							<view v-for="(fileUrl, index) in filesUrls" :key="index">
								<image :src="fileUrl" style="width: 100px; height: 100px;" />
							</view>
						</view>
					</scroll-view>
					<view class="modal-footer">
						<button form-type="submit" class="submit-button">提交</button>
						<button class="cancel-button" @click="showModal = false">取消</button>
					</view>
				</form>
			</view>
		</view>

		<view class="assess-list">
			<block v-for="(item, index) in assessList" :key="index">
				<view>
					<view style="display: flex;gap: 16rpx;">
						<image :src="item.avatar" mode="aspectFit"
							style="height: 100rpx; width: 100rpx; border-radius: 50%;" />
						<view>
							<view>{{ item.userName }}</view>
							<view>{{ item.createTime }}</view>
						</view>
					</view>
					<view style="margin-left: 116rpx;">
						<view>{{ item.description }}</view>
						<view>
							<image style="height:128px; width: 255px;" :src="item.reviewPicture" mode="aspectFit">
							</image>
						</view>
					</view>
				</view>
			</block>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';

	const app = getApp();
	const showModal = ref(false);
	const orderInfo = ref({});
	const assessList = ref([]);
	const formData = ref({
		description: '',
		score: 0
	});
	const filesUrls = ref([]); // 初始化filesUrls
	const tempFilePaths = ref({
		files: []
	}); // 初始化tempFilePaths

	const canPostReview = computed(() => assessList.value.length === 0);

	onLoad(option => {
		if (option.orderInfo) {
			const decodedOrderInfo = JSON.parse(decodeURIComponent(option.orderInfo));
			orderInfo.value = decodedOrderInfo;
			console.log("传递 的数据",orderInfo.value.escortInfo.id);
		} // 查询评估列表
		loadAssessList();
	});

	const loadAssessList = () => {
		app.globalData.utils.myrequest({
			myurl: '/assessInfo/list',
			data: {
				escortId: orderInfo.value.escortInfo.id
			},
			header: {
				'Authorization': uni.getStorageSync('token'),
				'Source-Platform': 'mini-program'
			},
			mysuccess: res => {
				assessList.value = res.data;
			},
			myfail: err => {
				console.log('获取评估列表错误', err);
				uni.showToast({
					title: '获取评估列表错误',
					icon: 'error'
				});
			}
		});
	};

	const handleModal = () => {
		if (canPostReview.value) {
			showModal.value = true;
		} else {
			uni.showToast({
				title: '您已经发布了评论，无法再次发布',
				icon: 'none'
			});
		}
	}

	const chooseFiles = () => {
		uni.chooseImage({
			count: 9,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: function(res) {
				filesUrls.value = [...filesUrls.value, ...res.tempFilePaths];
				tempFilePaths.value.files = [...tempFilePaths.value.files, ...res.tempFilePaths];
			}
		});
	};

	const handleSubmit = async () => {
		if (filesUrls.value.length === 0) {
			uni.showToast({
				title: '请上传评价图片',
				icon: 'none'
			});
			return;
		}

		const allFilePaths = [...(tempFilePaths.value.files || [])];
		const uploadPromises = allFilePaths.map(filePath => new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://192.168.1.160:18080/common/upload',
				filePath: filePath,
				name: 'files',
				header: {
					'Authorization': uni.getStorageSync('token'),
					'Source-Platform': 'mini-program'
				},
				success: res => {
					if (res.statusCode === 200) {
						resolve(JSON.parse(res.data).data[0]);
					} else {
						reject(new Error(`上传失败，状态码：${res.statusCode}`));
					}
				},
				fail: reject
			});
		}));

		let uploadedUrls;
		try {
			uploadedUrls = await Promise.all(uploadPromises);
		} catch (error) {
			uni.showToast({
				title: '文件上传失败',
				icon: 'none'
			});
			console.error('文件上传错误:', error);
			return;
		}

		const finalFormData = {
			...formData.value,
			escortId: orderInfo.value.escortInfo.id,
			reviewPicture: uploadedUrls.join(",")
		};
		app.globalData.utils.myrequest({
			myurl: '/assessInfo/save',
			method: 'POST',
			data: finalFormData,
			header: {
				'Authorization': uni.getStorageSync('token'),
				'Source-Platform': 'mini-program',
				'Content-Type': 'application/json'
			},
			mysuccess: res => {
				uni.showToast({
					title: '提交成功'
				});
				showModal.value = false;
				resetFormData();
				loadAssessList(); // 提交成功后重新加载评论列表
			},
			myfail: err => {
				uni.showToast({
					title: '提交失败',
					icon: 'none'
				});
				console.error("提交失败", err);
			}
		});
	};

	const resetFormData = () => {
		formData.value = {
			description: '',
			score: 0
		};
		filesUrls.value = [];
		tempFilePaths.value.files = [];
	};
</script>

<style scoped>
	/* 原有的样式代码保持不变 */
	.order-info {
		display: flex;
		align-items: center;
		padding: 20rpx;
	}

	.order-info image {
		width: 150rpx;
		height: 150rpx;
		margin-right: 20rpx;
	}

	.hospital-details {
		font-size: 27rpx;
		color: #333;
	}

	.order-info .hospital-details {
		padding-left: 20rpx;
	}

	.assess-list {
		padding: 20rpx;
		font-size: 28rpx;
	}

	.assess-item {
		border-bottom: 1px solid #ccc;
		padding: 10rpx 0;
	}

	.assess-item view {
		margin-bottom: 5rpx;
	}

	.assess-item image {
		width: 150rpx;
		height: 150rpx;
		margin-top: 10rpx;
	}

	.post-review-button[disabled] {
		background-color: #ccc;
		/* 根据需求调整禁用按钮的样式 */
	}
</style>